/*
 * File:   RoundRobinScheduler.cpp
 * Author: henrya
 *
 * Created on June 29, 2009, 6:12 AM
 */

#include "RoundRobinScheduler.h"
#include "Network.h"
#include <iostream>
using std::cout;
using std::endl;

RoundRobinScheduler::RoundRobinScheduler(Network* network, unsigned int q):OSScheduler(network),q(q),currRunningNodeIndex(0) {
}

RoundRobinScheduler::~RoundRobinScheduler() {
}

void RoundRobinScheduler::doScheduling(bool deliveredMsg) {
    if (m_curThread==NULL || doContextSwitch()) {
        Node* curr = network->getNodeAt(currRunningNodeIndex);
        notifyThreadChange(curr);
        tt->addQuanta(curr->getId(),q);
        curr->setQuanta(q);
    } else {
        //TODO update data?
    }
}

bool RoundRobinScheduler::doContextSwitch() {
    bool res=false;
    tt->updateUsedQuanta(m_curThread->getId(),m_curThread->getQuanta());
    if (currThreadStable()) {
        unsigned int nextNode=(currRunningNodeIndex+1)%network->getNodesCount();
        cout<<"Doing context switch... from "<<m_curThread->getId()<<" to "<<network->getNodeAt(nextNode)->getId()<<endl;
        currRunningNodeIndex=nextNode;
        res=true;
    }
    return res;
}

void RoundRobinScheduler::childReset() {
    currRunningNodeIndex=0;
}
